package com.linran.structure_algorithm.算法.lesson2_排序;

import java.time.Duration;
import java.time.LocalDateTime;

/**
 * 归并排序
 * //空间换时间
 */
public class SixMergeSort {

    public static void main(String[] args) {
        int base = 8000000;
        int[] arr = new int[base];
        for (int i = 0; i < base - 1; i++) {
            arr[i] = (int) (Math.random() * base);
        }
        LocalDateTime start = LocalDateTime.now();
        //线性增长，合并次数为arr.length - 1 次
        mergeSort(arr, 0, arr.length - 1, new int[arr.length]);// new int[arr.length]临时数组，多一份空间
        LocalDateTime end = LocalDateTime.now();
        System.out.println("排序后的数组");
        System.out.printf("耗时:%d毫秒%n", Duration.between(start, end).toMillis());
    }

    public static void mergeSort(int[] arr, int left, int right, int[] temp) {
        if (left < right) {
            int mid = (left + right) / 2;
            // 左递归
            mergeSort(arr, left, mid, temp);
            // 右递归
            mergeSort(arr, mid + 1, right, temp);
            // 合并
            merge(arr, left, mid, right, temp);
        }
        //到达末端，只剩一个数时结束为收敛条件
    }

    /**
     * 合并
     *
     * @param arr   原始数组
     * @param left  左边下标
     * @param mid   中间下标
     * @param right 右边下标
     * @param temp  临时数组
     */
    public static void merge(int[] arr, int left, int mid, int right, int[] temp) {
        int l = left;
        int r = mid + 1;
        int t = left; // temp下标
        //1.比较并拷贝至temp数组
        while (l <= mid && r <= right) {
            if (arr[l] < arr[r]) {
                temp[t] = arr[l];
                l++;
            } else {
                temp[t] = arr[r];
                r++;
            }
            t++;
        }
        //2.剩余数据拷贝,此时左右两列数组总有一列是完全拷贝成功
        while (l <= mid) {
            temp[t] = arr[l];
            l++;
            t++;
        }
        while (r <= right) {
            temp[r] = arr[r];
            r++;
            t++;
        }
        //3.将temp拷贝至原数组
        for (int c = left; c <= right; c++) {
            arr[c] = temp[c];
        }
    }
}
